//
//  DecimalCalcModel.m
//  DecimalCalc
//
//  Created by Ediz Turcan on 08.09.11.
//  Copyright 2011 DHBW Stuttgart. All rights reserved.
//

#import "DecimalCalcModel.h"

@implementation DecimalCalcModel

- (id)init
{
    self = [super init];
    if (self) {
        // Initialization code here.
    }
    return self;
}

- (NSString *) decToBin:(NSString *)inputValue {
    int multiplicator = 1;
    int inputV = inputValue.intValue;
    int tmpI = 0;
    NSUInteger stringL = 0;
    NSString *outputV = @"";
    NSString *oldoutput = @"";
    NSString *tmpString = @"";
    NSString *tmpString2 = @"";
    
    while ((multiplicator*2) <= inputV) {
        multiplicator *= 2;
    }
    while (multiplicator >= 1) {
        oldoutput = outputV;
        if((inputV / multiplicator) >= 1) {
            outputV = [NSString stringWithFormat:@"%@%i", oldoutput, 1];
            inputV -= multiplicator;
        }
        else {
            outputV = [NSString stringWithFormat:@"%@%i", oldoutput, 0];
        }
        multiplicator /= 2;
    }
    
    stringL = outputV.length;
    tmpString = outputV;
    tmpI = (int)stringL % 4;
    if(tmpI == 0) {
        tmpI = 4;
    }
    for(int i = 0; i < (4 - tmpI); i++) {
        tmpString = [NSString stringWithFormat:@"%i%@", 0, tmpString];
    }
    outputV = tmpString;    
    
    tmpI = (int)outputV.length / 4 - 1;
    tmpString = [NSString stringWithFormat:@""];
    for(int i = 0; i <= tmpI; i++) {
        if(i == 0) {
            tmpString = [NSString stringWithFormat:@"%@ ", [outputV substringToIndex:4]];
        }
        else {
            tmpString2 = [NSString stringWithFormat:@"%@", [outputV substringFromIndex:i*4]];
            tmpString2 = [tmpString2 substringToIndex:4];
            tmpString = [NSString stringWithFormat:@"%@%@ ", tmpString, tmpString2];
        }
    }
    tmpI = (int)tmpString.length - 1;
    outputV = [tmpString substringToIndex:tmpI];
    return outputV;
}

- (NSString *) calculateNewValue:(methode)methode inputValue:(NSString *)inputValue {
    
    switch (methode) {
        case dec2bin:
            return [self decToBin:inputValue];
            break;
    }
    
}

@end
